package cn.com.sbell.vss.commander;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import cn.com.sbell.vss.ICommander;
import cn.com.sbell.vss.Response;
import cn.com.sbell.vss.csg.heartbeat.HeartBeatHandler;
import cn.com.sbell.vss.util.XmlUtil;

public class ShowMemory implements ICommander {
	private static final Log log = LogFactory.getLog(ShowMemory.class);

	private HeartBeatHandler heartBeatHandler;

	public Response execute(HttpServletRequest request) {
		log.debug("Show Memory ...");
		Response response = Response.createResponse(request);
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("parameters");

		long maxMemory = Runtime.getRuntime().maxMemory();
		long totalMemory = Runtime.getRuntime().totalMemory();
		long freeMemory = Runtime.getRuntime().freeMemory();
		long useMemory = totalMemory - freeMemory;
		XmlUtil.addElement(root, "maxMemory", maxMemory + "(" + maxMemory /1024/1024 + "m)");
		XmlUtil.addElement(root, "totalMemory", totalMemory + "(" + totalMemory /1024/1024 + "m)");
		XmlUtil.addElement(root, "freeMemory", freeMemory + "(" + freeMemory /1024/1024 + "m)");
		XmlUtil.addElement(root, "useMemory", useMemory + "(" + useMemory /1024/1024 + "m)");
		XmlUtil.addElement(root, "use2max", (useMemory * 100 / maxMemory) + "%");

		XmlUtil.addElement(root, "holdSessionSize", heartBeatHandler.holdNum.longValue());
		XmlUtil.addElement(root, "createSessionNumber", heartBeatHandler.createNum);
		XmlUtil.addElement(root, "closeSessionNumber", heartBeatHandler.closeNum);

		response.setParameters(doc.asXML());
		return response;
	}

	public HeartBeatHandler getHeartBeatHandler() {
		return heartBeatHandler;
	}

	public void setHeartBeatHandler(HeartBeatHandler heartBeatHandler) {
		this.heartBeatHandler = heartBeatHandler;
	}
}
